package com.qingzhu.service.impl;

import com.qingzhu.dao.ReceivingAddressDao;
import com.qingzhu.dao.impl.ReceivingAddressDaoImpl;
import com.qingzhu.pojo.Address;
import com.qingzhu.pojo.ReceivingAddress;
import com.qingzhu.service.AddressService;
import com.qingzhu.service.ReceivingAddressService;

import java.util.List;

public class ReceivingAddressServiceImpl implements ReceivingAddressService {
    ReceivingAddressDao receivingAddressDao = new ReceivingAddressDaoImpl();
    AddressService addressService = new AddressServiceImpl();

    @Override
    public List<ReceivingAddress> findAll(int userId) {
        List<ReceivingAddress> addressList = receivingAddressDao.findAll(userId);
        addressList.forEach(a -> {
            Address defaultAddress = addressService.findDefaultAddress(a.getRegionUrl());
            a.setRegion(defaultAddress);
        });
        return addressList;
    }

    @Override
    public int addOneReceivingAddress(ReceivingAddress receivingAddress) {
        // 如果用户没有添加地址的别名，则创建一个别名（用户名+省名）
        if (receivingAddress.getAddressAlias() == null || receivingAddress.getAddressAlias() == "") {
            Address defaultAddress = addressService.findDefaultAddress(receivingAddress.getRegionUrl());
            String addressAlias = receivingAddress.getConsignee()+" "+defaultAddress.getProvinces().getProvince();
            receivingAddress.setAddressAlias(addressAlias);
        }
        return receivingAddressDao.addOneReceivingAddress(receivingAddress);
    }

    @Override
    public int updateOneReceivingAddress(ReceivingAddress receivingAddress) {
        // 如果用户没有添加地址的别名，则创建一个别名（用户名+省名）
        if (receivingAddress.getAddressAlias() == null || receivingAddress.getAddressAlias() == "") {
            Address defaultAddress = addressService.findDefaultAddress(receivingAddress.getRegionUrl());
            String addressAlias = receivingAddress.getConsignee()+" "+defaultAddress.getProvinces().getProvince();
            receivingAddress.setAddressAlias(addressAlias);
        }
        return receivingAddressDao.updateOneReceivingAddress(receivingAddress);
    }

    @Override
    public int delOneReceivingAddress(int id) {
        int address = receivingAddressDao.delOneReceivingAddress(id);
        return address;
    }

    @Override
    public void updateDefaultDreceivingAddress(int id,int userId) {
        // 查找到用户名下的所有地址
        List<ReceivingAddress> addressList = receivingAddressDao.findAll(userId);
        // 将用户指定的地址修改为默认地址
        addressList.forEach(a -> {
            if (a.getId() == id) {
                receivingAddressDao.updateDefaultDreceivingAddress(0,a.getId());
            }else {
                receivingAddressDao.updateDefaultDreceivingAddress(1,a.getId());
            }
        });
    }
}
